import { nextTick, reactive, computed } from "vue"
// 校验函数
import { validateRequired, getControlByField, formatTree } from "@/utils/index"
import { useSelectAsync } from "@/hook"
import { bookcreate, bookdetailed, bookupdate } from "@/api"
// api
import { uploadImage } from "@/api";
export function useIndex(formRef, props) {
  const { useGetLibraryAll, useGetFrameAll, useGetBookCategoryAll } = useSelectAsync()
  const useState = reactive({
    controlList: [
      {
        label: "书籍封面",
        field: "book_img",
        control: "uploadImage",
        config: {
          size: 5,
          buttonText: "上传头像",
          onSuccess: (data) => formRef.value.validateFields(['book_img']),
          defaultImage: ""
        },
        // rules: [validateRequired('请上传书籍封面')]
      },
      {
        label: "图书名称",
        field: "book_name",
        control: "input",
        maxlength: 20,
        col: 12,
      },
      {
        label: "ISBN编码",
        field: "book_isbn",
        control: "input",
        maxlength: 20,
        col: 12,
      },
      {
        label: "作者",
        field: "author",
        control: "input",
        maxlength: 20,
        col: 12,
      },
      {
        label: "图书数量",
        field: "count",
        control: "inputnumber",
        maxlength: 20,
        col: 12,
      },
      {
        label: "出版社",
        field: "press",
        control: "input",
        maxlength: 20,
        col: 12,
      },
      {
        label: "出版日期",
        field: "publication_date",
        control: "date",
        col: 12,
        showTime: false,
        valueFormat: "YYYY-MM-DD"
      },
      {
        label: "印次",
        field: "impression",
        control: "inputnumber",
        col: 12,
      },
      {
        label: "版次",
        field: "version_number",
        control: "inputnumber",
        col: 12,
      },
      {
        label: "页数",
        field: "pages",
        control: "inputnumber",
        col: 12,
      },
      {
        label: "所属藏馆",
        field: "library_ids",
        control: "select",
        col: 12,
        name: "library_name",
        id: "id",
        optionsAsync: useGetLibraryAll,
        mode: "multiple"
      },
      {
        label: "层架",
        field: "layer_ids",
        control: "select",
        col: 12,
        name: "frame_name",
        id: "frame_id",
        optionsAsync: useGetFrameAll,
        mode: "multiple"
      },
      {
        label: "图书分类",
        field: "book_category",
        control: "select",
        col: 12,
        name: "category_name",
        id: "category_id",
        optionsAsync: useGetBookCategoryAll,
        mode: "multiple"
      },
      {
        label: "省市区",
        field: "area",
        control: "area",
        col: 12,
        name: "name",
        id: "code",
        defaultValue: []
        // rules: [validateRequired('请选择省市区')]
      },
      {
        label: "详细地址",
        field: "address",
        control: "textarea",
        col: 24,
      },
      {
        label: "书籍介绍",
        field: "introduce",
        control: "editor",
      },
    ],
    fields: {
      book_img: "",
      book_name: "",
      book_isbn: "",
      author: "",
      count: "",
      press: "",
      publication_date: "",
      impression: "",
      version_number: "",
      pages: "",
      layer_ids: [],
      library_ids: [],
      book_category: [],
      province: "",
      city: "",
      area: "",
      address: "",
      introduce: "",
    }
  })

  const id = computed(() => props.row?.book_id)
  // title
  const title = computed(() => id.value ? '编辑图书' : "添加图书")

  const useOkAsync = () => {
    return new Promise((resolve, reject) => {
      // 表单校验
      formRef.value.validataForm().then(() => {
        const req = useState.fields
        // 存在省市区
        if (req.area && req.area.length) {
          req.province = req.area[0]
          req.city = req.area[1]
          req.area = req.area[2]
        }

        if(id.value) {
          bookupdate({
            ...req,
            book_id: id.value
          }).then(() => {
            console.log(222)
            resolve()
          }).catch(() => {
            reject()
          })
        }else{
          bookcreate(req).then(() => {
            console.log(222)
            resolve()
          }).catch(() => {
            reject()
          })
        }

        
      }).catch(() => {
        reject()
      })
    })
  }




  const useBookDetailed = () => {
    return new Promise((resolve, reject) => {
      bookdetailed({id: id.value}).then(res => {
        console.log('res', res)
        const data = res.content
        // 封面
        const img = data.book_img
        useState.controlList[0].config.defaultImage = img
        useState.fields.book_img = img
        // 书名
        useState.fields.book_name = data.book_name
        useState.fields.book_isbn = data.book_isbn
        useState.fields.author = data.author
        useState.fields.count = data.count
        useState.fields.press = data.press
        useState.fields.publication_date = data.publication_date
        useState.fields.impression = data.impression
        useState.fields.version_number = data.version_number
        useState.fields.pages = data.pages
        useState.fields.library_ids = data.library_ids
        useState.fields.layer_ids = data.layer_ids
        useState.fields.book_category = data.book_category
        useState.fields.area = data.area
        useState.fields.address = data.address
        useState.fields.introduce = data.introduce
        // 省市区
        const control = getControlByField(useState.controlList, 'area')
        control.defaultValue = formatTree(data.area_item, 'code', 'parent_id')
        // 先处理数据，然后再显示
        resolve()
      }).catch(() => {
        reject()
      })
    })
    
  }

  /** 初始加载 */
  const useInnerLoading = () => {
    return new Promise((resolve, reject) => { // then，catch
      if(id.value) {
        useBookDetailed().then(() => {
          
          resolve()
        }).catch(() => {
          reject()
        })
        return
      }
      // 不存在ID
      resolve()
    })
  }

  return {
    title,
    useState,
    useOkAsync,
    useInnerLoading,
  }
}